﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Media;
using System.IO;

namespace FMSpaceShooter.GameData
{
    public class AudioManager : GameComponent
    {
        private int currentSongIndex = 0;
        private const string effectsDirectory = "/AudioFX";
        private const string bgDirectory = "/AudioBG";
        private Dictionary<string, SoundEffect> audioFXs = new Dictionary<string, SoundEffect>();
        private List<Song> audioBGs = new List<Song>();

        public AudioManager(Game1 game)
            : base(game)
        {
            
            foreach (var file in Directory.GetFiles(Game.Content.RootDirectory + effectsDirectory, "*.*", SearchOption.AllDirectories))
            {
                string filePart = file.Replace("Content/", "").Replace(".xnb", "").Replace('\\','/');
                audioFXs.Add(filePart, game.Content.Load<SoundEffect>(filePart));
            }

            foreach (var file in Directory.GetFiles(Game.Content.RootDirectory + bgDirectory, "*.*", SearchOption.AllDirectories))
            {
                string filePart = file.Replace("Content/", "").Replace(".xnb", "").Replace(".wma", "").Replace('\\', '/');
                audioBGs.Add(game.Content.Load<Song>(filePart));
            }

            Random rand = new Random();

            currentSongIndex = rand.Next(0, audioBGs.Count);

            MediaPlayer.Volume = .2f;
            MediaPlayer.Play(audioBGs[currentSongIndex++]);
            MediaPlayer.MediaStateChanged += (object o, EventArgs e) => {
                if (MediaPlayer.State == MediaState.Stopped) {
                    MediaPlayer.Play(audioBGs[currentSongIndex++ % audioBGs.Count]); 
                } 
            };
        }

        public void PlayFX(string name)
        {
            if (audioFXs.ContainsKey(name))
            {
                audioFXs[name].Play(.2f, -.5f, 0f);
            }
        }

    }
}
